package cn.gov.pbc.gd.credit.web.controller.realuser;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liu.jbase.ResultVo;
import com.liu.jbase.controller.impl.BaseControllerImpl;
import com.liu.tools.MD5Util;
import com.liu.tools.RandomUtil;

import cn.gov.pbc.gd.credit.center.service.user.ICCUserService;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.user.service.realuser.IRealUserService;
import cn.gov.pbc.gd.credit.vo.center.ReqCCUserVo;
import cn.gov.pbc.gd.credit.vo.center.ResCCUserVo;
import cn.gov.pbc.gd.credit.vo.realuser.RealUserVo;
import cn.gov.pbc.gd.credit.vo.realuser.ResRealUserVo;

@Controller
@RequestMapping("/realUser")
public class RealUserController extends BaseControllerImpl<ResRealUserVo, RealUserVo, IRealUserService> {
    @Autowired
    private IRealUserService realUserService;

    @Autowired
    private ICCUserService ccUserService;

    private static Logger logger = LoggerFactory.getLogger(RealUserController.class);

    /**
     * 查询没有关联虚拟用户的真实用户
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/queryAllRealUserWithOutUser")
    public ResultVo<List<RealUserVo>> queryAllRealUserWithOutUser(String userId) throws Exception {
        return realUserService.queryAllRealUserWithOutUser(userId);
    }

    /**
     * 判断当前用户是否重名或者当前用户是否既是查询员又是异议处理员
     *
     * @param userName
     * @return
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping("/queryThisUserShowLoginNameOrNot")
    public ResultVo queryThisUserShowLoginNameOrNot(String userName) {
        return realUserService.queryThisUserShowLoginNameOrNot(userName);
    }

    /**
     * 更新真实用户
     *
     * @return
     * @throws Exception 用当前真实用户先登陆征信中心，如果登陆失败，提示用户；
     *                   如果登陆成功，并且真实用户的密码有修改，那么调用征信中心的密码修改功能
     *                   如果登陆成功，密码没有修改，那么只调用前置系统修改真实用户
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping("/updateRealUser")
    public ResultVo updateRealUser(RealUserVo realUserVo, HttpServletRequest request, HttpSession httpSession)
            throws Exception {
        //realUserService.modifyPwdInFixedTime(new UserVo(), request);
        ResultVo resultVo = null;
        // 查询当前真实用户的详细信息
        ResultVo<ResRealUserVo> realUserRes = realUserService.findById(realUserVo.getId(), request);
        if (realUserRes.getData().getUserPwd().equals(realUserVo.getUserPwd())) {// 密码没有修改（登陆人行征信中心）
            realUserVo.setAccount(realUserRes.getData().getAccount());
            resultVo = loginCreditCenterAndUpdatePassword(realUserVo, false, request, httpSession);
        } else {// 密码有改动 （登陆人行征信中心，并修改征信中心的密码）
            resultVo = loginCreditCenterAndUpdatePassword(realUserVo, true, request, httpSession);
        }
        if (!CodeConstant.SUCCESS.equals(resultVo.getCode())) {
            return resultVo;
        }
        realUserVo.setUpdatePwdTime(new Date());
        return super.update(realUserVo, request);
    }

    /**
     * 保存真实用户
     *
     * @param realUserVo
     * @param request
     * @return
     * @throws Exception 保存真实用户之前，用该用户先登陆征信中心； 如果登陆失败，提示征信中心不存在该用户
     *                   如果登陆成功，随机生成一个密码修改征信中心的用户的密码,随后在前置系统保存该真实用户
     */
    @SuppressWarnings("rawtypes")
    @ResponseBody
    @RequestMapping("/saveRealUser")
    public ResultVo saveRealUser(RealUserVo realUserVo, HttpServletRequest request, HttpSession httpSession)
            throws Exception {
        ResultVo resCCUserVo = loginCreditCenterAndUpdatePassword(realUserVo, true, request, httpSession);
        if (!CodeConstant.SUCCESS.equals(resCCUserVo.getCode())) {
            return resCCUserVo;
        }
        // 保存真实用户
        realUserVo.setUserPwd(resCCUserVo.getMsg());
        return super.save(realUserVo, request);
    }

    /**
     * 登陆人行征信中心并修改人行征信中心的密码
     *
     * @param realUserVo
     * @param request
     * @param httpSession
     * @param flag        是否修改征信中心的密码
     * @return
     * @throws UnsupportedEncodingException
     */
    @SuppressWarnings("rawtypes")
    public ResultVo loginCreditCenterAndUpdatePassword(RealUserVo realUserVo, boolean flag, HttpServletRequest request,
                                                       HttpSession httpSession) throws UnsupportedEncodingException {
        ResultVo resCCUserVo = null;
        // 登陆人行征信中心
        ReqCCUserVo loginVo = new ReqCCUserVo();
        loginVo.setPassword(realUserVo.getUserPwd());
        loginVo.setUserid(realUserVo.getAccount());
        ResultVo<ResCCUserVo> resultLogin = ccUserService.login(loginVo, request);
        logger.info("登陆人行征信中心，接口返回的结果为" + resultLogin.getMsg());
        String password = RandomUtil.randomStr(11);
        if (flag) {
            // 修改人行征信中心的密码
            ReqCCUserVo ccUserVo = new ReqCCUserVo();
            ccUserVo.setOldpassword(realUserVo.getUserPwd());
            ccUserVo.setNewpasswordvalid(password);
            ccUserVo.setPassword(password);
            if (resultLogin.getData() != null) {
                ccUserVo.setCookies(resultLogin.getData().getCookies());
            }
            ccUserVo.setUserid(realUserVo.getAccount());
            logger.info("请求cookies******************:" + ccUserVo.getCookies());
            resCCUserVo = ccUserService.modifyPwd(ccUserVo, request);

            if (!CodeConstant.SUCCESS.equals(resCCUserVo.getCode())) {
                logger.info("修改征信中心密码失败，失败信息为" + resCCUserVo.getMsg());
                return resCCUserVo;
            }
            resCCUserVo.setMsg(password);
        } else {
            logger.info("只登陆人行征信中心，不进行密码修改的功能");
        }


        return resCCUserVo;
    }
}
